package com.itemp.wifidirectsend;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import androidx.annotation.NonNull;

/***
 * WiFi Direct Client
 *
 * 客户端发送文件
 */
public class FileSenderActivity extends BaseActivity implements DirectActionListener {
    private static final String TAG = "SendFileActivity";
    private static final int CODE_SEND_WIFI_CONFIG = 0;
    private static final int CODE_SCAN_SEND_FILES = 1;
    private static final int CODE_SEND_FILES = 2;
    private static final String WIFI_CONFIG_FILE= "WiFiConfig";
    private String wifiConfigFilePath;
    private boolean wifiP2pEnabled;
    private WifiP2pInfo wifiP2pInfo;
    private List<WifiP2pDevice> wifiP2pDeviceList;
    private DeviceAdapter deviceAdapter;
    private WifiP2pDevice mWifiP2pDevice;
    private WifiP2pManager mWifiP2pManager;
    private WifiP2pManager.Channel mChannel;
    private DirectBroadcastReceiver broadcastReceiver;
    private TextView tvDeviceState, tvConnectionStatus;
    private Button btnSendWifiConfig, btnChooseFile, btnDirectDiscover;
    private ListView rvDeviceList;
    private boolean isP2pConnect;
    private EditText ssidEt,passwordEt;
    private String wifiSSID,wifiPassword;
    private String p2pAddress;

    private String[] permissions = {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.CHANGE_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_file);
        Log.d(TAG, "---------onCreate");
        requestPermission(permissions);
        initDevice();
    }


    private void initDevice() {
        findViewById(R.id.scan_send_file).setOnClickListener(view -> {
            Intent intent = new Intent(FileSenderActivity.this, QRScannerActivity.class);
            startActivityForResult(intent, CODE_SCAN_SEND_FILES);
        });
        tvConnectionStatus = findViewById(R.id.tv_connection_status);
        btnDirectDiscover = findViewById(R.id.btn_search_wifi_device);
        btnDirectDiscover.setOnClickListener(view -> searchWifiP2pDevice());
        btnChooseFile = findViewById(R.id.btn_select_file);
        btnChooseFile.setEnabled(false);
        btnChooseFile.setOnClickListener(view -> sendFile());
        rvDeviceList = findViewById(R.id.wifi_device_list);
        wifiP2pDeviceList = new ArrayList<WifiP2pDevice>();
        mWifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        mChannel = mWifiP2pManager.initialize(this, getMainLooper(), this);
        broadcastReceiver = new DirectBroadcastReceiver(mWifiP2pManager, mChannel, this);
        registerReceiver(broadcastReceiver, DirectBroadcastReceiver.getIntentFilter());
        //搜索周边设备，回调函数用于通知方法是否调用成功
        //搜索结束后，系统就会触发 WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION 广播，
        //此时就可以调用 requestPeers 方法获取设备列表信息，此处用 RecyclerView 展示列表，
        //在onPeersAvailable 方法刷新列表
        if (!wifiP2pEnabled) {
            Log.d(TAG, "打开WiFi");
        }
        searchWifiP2pDevice();
        deviceAdapter = new DeviceAdapter(this, wifiP2pDeviceList);
        rvDeviceList.setAdapter(deviceAdapter);
        deviceAdapter.setOnItemClickListener(position -> {
            mWifiP2pDevice = wifiP2pDeviceList.get(position);
            if (mWifiP2pDevice != null && !isP2pConnect) {
                connect(mWifiP2pDevice);
            }
        });
        ssidEt = findViewById(R.id.ssid_et);
        passwordEt = findViewById(R.id.password_et);

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo != null) {
            String tempString = wifiInfo.getSSID();
            wifiSSID = tempString.substring(1, tempString.length() - 1);
            ssidEt.setText(wifiSSID);
            Log.d(TAG, "wifiSSID: " + wifiSSID);
        }

        btnSendWifiConfig = findViewById(R.id.btn_send_wifi_config);
        btnSendWifiConfig.setEnabled(false);
        btnSendWifiConfig.setOnClickListener(view -> {
            wifiSSID = ssidEt.getText().toString().trim();
            wifiPassword = passwordEt.getText().toString().trim();
            writeExternalFile(wifiConfigFilePath, wifiSSID + ";" + wifiPassword + ";");
            p2pSendFile(wifiConfigFilePath);
        });

        wifiConfigFilePath = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath()
                + File.separator
                + WIFI_CONFIG_FILE;

        writeExternalFile(wifiConfigFilePath, wifiSSID);

    }

    @SuppressLint("MissingPermission")
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "---------onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "---------onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "---------onPause");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "---------onRestart");
    }

    @SuppressLint("MissingPermission")
    private void searchWifiP2pDevice() {
        showLoadingDialog("Searching for wifi p2p devices...");
        btnDirectDiscover.setEnabled(false);
        mWifiP2pManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.e(TAG, "Discovery onSuccess");
            }

            @Override
            public void onFailure(int reasonCode) {
                Log.e(TAG, "Discovery onFailure");
                btnDirectDiscover.setEnabled(true);
                dismissLoadingDialog();
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    public void onChannelDisconnected() {
        Log.d(TAG, "onDisconnection");
        wifiP2pDeviceList.clear();
        deviceAdapter.notifyDataSetChanged();
        tvConnectionStatus.setText("");
        wifiP2pInfo = null;
    }

    @Override
    public void wifiP2pEnabled(boolean enabled) {
        wifiP2pEnabled = enabled;
    }

    @Override
    public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
        btnDirectDiscover.setEnabled(true);
        dismissLoadingDialog();
        wifiP2pDeviceList.clear();
        deviceAdapter.notifyDataSetChanged();
//        btnDisconnect.setEnabled(true);
        btnChooseFile.setEnabled(true);
        btnSendWifiConfig.setEnabled(true);
        Log.e(TAG, "onConnectionInfoAvailable");
        Log.e(TAG, "onConnectionInfoAvailable groupFormed: " + wifiP2pInfo.groupFormed);
        Log.e(TAG, "onConnectionInfoAvailable isGroupOwner: " + wifiP2pInfo.isGroupOwner);
        Log.e(TAG, "onConnectionInfoAvailable getHostAddress: " + wifiP2pInfo.groupOwnerAddress.getHostAddress());
        StringBuilder stringBuilder = new StringBuilder();

        if (mWifiP2pDevice != null) {
            stringBuilder.append("Connected device：");
            stringBuilder.append(mWifiP2pDevice.deviceName);
            stringBuilder.append("\n");
            stringBuilder.append("Connected device mac：");
            stringBuilder.append(mWifiP2pDevice.deviceAddress);
        }else{
            stringBuilder.append("Connected device mac：");
            stringBuilder.append(p2pAddress);
        }
//        stringBuilder.append("\n");
//        stringBuilder.append("isGroupOwner?：");
//        stringBuilder.append(wifiP2pInfo.isGroupOwner ? "GroupOwner" : "Not GroupOwner");
        stringBuilder.append("\n");
        stringBuilder.append("GroupOwner IP：");
        stringBuilder.append(wifiP2pInfo.groupOwnerAddress.getHostAddress());
        tvConnectionStatus.setText(stringBuilder);
        if (wifiP2pInfo.groupFormed && !wifiP2pInfo.isGroupOwner) {
            this.wifiP2pInfo = wifiP2pInfo;
            //服务器端和客户端已经通过 Wifi P2P 连接在了一起，
            // 客户端也获取到了服务器端的IP地址，在选取好待发送的文件后就可以主动发起对服务器端的连接请求了
            isP2pConnect = true;
            p2pSendFile(wifiConfigFilePath);
        }
    }

    private void p2pSendFile(String filePath){
        File file = new File(filePath);
        if (file.exists() && wifiP2pInfo != null) {
            FileTransfer fileTransfer = new FileTransfer(file.getPath(), file.length());
            Log.e(TAG, "待发送的文件：" + fileTransfer);
            new WifiClientTask(this, fileTransfer).execute(wifiP2pInfo.groupOwnerAddress.getHostAddress());
        }
    }

    private void writeExternalFile(String fileName, String content){
        String storageState = Environment.getExternalStorageState();
        FileOutputStream fileOutputStream = null;
        BufferedWriter bufferedWriter = null;
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            try {
                fileOutputStream = new FileOutputStream(fileName);
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
                bufferedWriter.write(content);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (bufferedWriter != null){
                    try {
                        bufferedWriter.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void writeFile(String data, String fileName){
        FileOutputStream fileOutputStream = null;
        BufferedWriter bufferedWriter = null;
        try{
            fileOutputStream = openFileOutput(fileName,Context.MODE_PRIVATE);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            bufferedWriter.write(data);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (bufferedWriter != null){
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private void sendFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, CODE_SEND_FILES);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_SEND_WIFI_CONFIG:
                    p2pAddress = data.getStringExtra("SCAN_RESULT");
                    break;
                case CODE_SCAN_SEND_FILES:
                    p2pAddress = data.getStringExtra("SCAN_RESULT");
                    if(!isP2pConnect){
                        connectP2pByAddress(p2pAddress);
                    }
                    searchWifiP2pDevice();

                    Log.d(TAG, "result = " + p2pAddress);
                    break;
                case CODE_SEND_FILES:
                    Uri uri = data.getData();
                    if (uri != null) {
                        String path = getPath(this, uri);
                        if (path != null) {
                            File file = new File(path);
                            if (file.exists() && wifiP2pInfo != null) {
                                FileTransfer fileTransfer = new FileTransfer(file.getPath(), file.length());
                                Log.e(TAG, "待发送的文件：" + fileTransfer);
                                new WifiClientTask(this, fileTransfer).execute(wifiP2pInfo.groupOwnerAddress.getHostAddress());
                            }
                        }
                    }
                    break;
            }
        }
    }


    @SuppressLint("NewApi")
    public String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                Log.d(TAG, id);
                if (id != null && id.startsWith("raw:")) {
                    return id.substring(4);
                }
                String[] contentUriPrefixesToTry = new String[]{
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads"
                };
                for (String contentUriPrefix : contentUriPrefixesToTry) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                    try {
                        String path = getDataColumn(context, contentUri, null, null);
                        if (path != null && !path.equals("")) {
                            return path;
                        }
                    } catch (Exception e) {
                    }
                }
                String fileName = getFileName(context, uri);
                if (!fileName.toLowerCase().contains("/storage/emulated/0/Download/".toLowerCase())) {
                    fileName = "/storage/emulated/0/Download/" + fileName;
                }
                return "fileName = " + fileName;
                /*
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
               // Toast.makeText(MainActivity.this,  " Long.valueOf(id) "+Long.valueOf(id), Toast.LENGTH_SHORT).show();
                return getDataColumn(context, contentUri, null, null);
                */
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return "NULL";
    }

    public String getFileName(@NonNull Context context, Uri uri) {
        String mimeType = context.getContentResolver().getType(uri);
        String filename = null;
        if (mimeType == null && context != null) {
           /* String path = getPath(context, uri);
            if (path == null) {
                filename = getName(uri.toString());
            } else {
                File file = new File(path);
                filename = file.getName();
            }*/
        } else {
            Cursor returnCursor = context.getContentResolver().query(uri, null,
                    null, null, null);
            if (returnCursor != null) {
                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);

                Log.d("FUCKFUCK nameIndex", "" + nameIndex);
                returnCursor.moveToFirst();
                filename = returnCursor.getString(nameIndex);
                returnCursor.close();
            }
        }
        return filename;
    }

    public String getName(String filename) {
        if (filename == null) {
            return null;
        }
        int index = filename.lastIndexOf('/');
        return filename.substring(index + 1);
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    @Override
    public void onDisconnection() {
        Log.d(TAG, "onDisconnection");
//        btnDisconnect.setEnabled(false);
        btnChooseFile.setEnabled(false);
        btnSendWifiConfig.setEnabled(false);
        wifiP2pDeviceList.clear();
        deviceAdapter.notifyDataSetChanged();
        tvConnectionStatus.setText("");
        wifiP2pInfo = null;
        isP2pConnect = false;
    }

    @Override
    public void onSelfDeviceAvailable(WifiP2pDevice wifiP2pDevice) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("deviceName: " + wifiP2pDevice.deviceName);
        stringBuilder.append("\n");
        stringBuilder.append("deviceAddress: " + wifiP2pDevice.deviceAddress);
        stringBuilder.append("\n");
        stringBuilder.append(
                "status: " + wifiP2pDevice.status + " " + WifiP2pUtils.getDeviceStatus(
                        wifiP2pDevice.status
                )
        );
        tvConnectionStatus.setText(stringBuilder.toString());
    }

    @Override
    public void onPeersAvailable(Collection<WifiP2pDevice> wifiP2pDeviceList) {
        Log.e(TAG, "onPeersAvailable :" + wifiP2pDeviceList.size());
        this.wifiP2pDeviceList.clear();
        this.wifiP2pDeviceList.addAll(wifiP2pDeviceList);
        deviceAdapter.notifyDataSetChanged();
        dismissLoadingDialog();
        btnDirectDiscover.setEnabled(true);

        /*for (WifiP2pDevice wifiP2pDevice:wifiP2pDeviceList){
            Log.d(TAG, wifiP2pDevice.deviceAddress + "," + p2pAddress);
            if (wifiP2pDevice.deviceAddress.equals(p2pAddress)){
                mWifiP2pDevice = wifiP2pDevice;
                if (mWifiP2pDevice != null && !isP2pConnect) {
                    connect(mWifiP2pDevice);
                }
            }
        }*/
    }

    @SuppressLint("MissingPermission")
    //通过点击事件选中群主（服务器端）设备，通过 connect 方法请求与之进行连接
    private void connect(WifiP2pDevice mWifiP2pDevice) {
        disconnect();
        WifiP2pConfig config = new WifiP2pConfig();
        if (config.deviceAddress != null && mWifiP2pDevice != null) {
            config.deviceAddress = mWifiP2pDevice.deviceAddress;
            Log.d(TAG,"deviceAddress = " + mWifiP2pDevice.deviceAddress);
            config.wps.setup = WpsInfo.PBC;
            showLoadingDialog("Connecting device:" + mWifiP2pDevice.deviceName);
            Log.d(TAG, "正在连接deviceName: " + mWifiP2pDevice.deviceName);
            mWifiP2pManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
                @Override
                public void onSuccess() {
                    btnDirectDiscover.setEnabled(true);
                    dismissLoadingDialog();
                    Log.e(TAG, "connect onSuccess");
                }

                @Override
                public void onFailure(int reason) {
                    btnDirectDiscover.setEnabled(true);
                    showToast("connect onFailure ,reason = " + reason);
                    dismissLoadingDialog();
                    isP2pConnect = false;
                }
            });
        }
    }
    @SuppressLint("MissingPermission")
    private void connectP2pByAddress(String p2pAddress){
        disconnect();
        WifiP2pConfig config = new WifiP2pConfig();
        if (config.deviceAddress != null && p2pAddress != null) {
            config.deviceAddress = p2pAddress;
            config.wps.setup = WpsInfo.PBC;
            showLoadingDialog("Connecting device:" + p2pAddress);
            Log.d(TAG, "正在连接deviceName: " + p2pAddress);
            mWifiP2pManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
                @Override
                public void onSuccess() {
                    btnDirectDiscover.setEnabled(true);
                    dismissLoadingDialog();
                    Log.e(TAG, "connect onSuccess");
                }

                @Override
                public void onFailure(int reason) {
                    btnDirectDiscover.setEnabled(true);
                    showToast("connect onFailure ,reason = " + reason);
                    dismissLoadingDialog();
                    isP2pConnect = false;
                }
            });
        }
    }

    private void disconnect() {
        mWifiP2pManager.cancelConnect(mChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.e(TAG, "disconnect onSuccess");
            }

            @Override
            public void onFailure(int i) {
                Log.e(TAG, "disconnect onSuccess");
                tvConnectionStatus.setText("");
                btnSendWifiConfig.setEnabled(false);
                btnChooseFile.setEnabled(false);
            }
        });
        mWifiP2pManager.removeGroup(mChannel, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        disconnect();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
    }
}